package com.zhuxulin.midi.event.meta;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.zhuxulin.midi.event.MidiEvent;
import com.zhuxulin.midi.util.ReadVarLen;
/**
 * FF 59 event
 * @author ZhuXulin
 *
 */
public class KeySignature extends MetaEvent {

	public static final int SCALE_MAJOR = 0;
	public static final int SCALE_MINOR = 1;
	
	private int mKey;
	private int mScale;
	
	public KeySignature(long tick, long delta, int key, int scale) {
		super(tick, delta, MetaEvent.KEY_SIGNATURE, new ReadVarLen(2));
		
		this.setKey(key);
		mScale = scale;
	}
	
	public void setKey(int key) {
		mKey = (byte)key;
		
		if(mKey < -7) mKey = -7;
		else if(mKey > 7) mKey = 7;
	}
	public int getKey() {
		return mKey;
	}
	
	public void setScale(int scale) {
		mScale = scale;
	}
	public int getScale() {
		return mScale;
	}

	@Override
	protected int getEventSize() {
		return 5;
	}
	
	@Override
	public void writeToFile(OutputStream out) throws IOException {
		super.writeToFile(out);
		
		out.write(2);
		out.write(mKey);
		out.write(mScale);
	}
	@Override
	public byte[] getCmd() {
		cmd = new byte[] { (byte) 0xFF, 0x59, 0x02, (byte) mKey, (byte) mScale };
		return cmd;
	}
	public static KeySignature parseKeySignature(long tick, long delta, InputStream in) throws IOException {
		
		in.read();		// Size = 2;
		int key = in.read();
		int scale = in.read();
		
		return new KeySignature(tick, delta, key, scale);
	}

	@Override
	public int compareTo(MidiEvent other) {
		
		if(mTick != other.getTick()) {
			return mTick < other.getTick() ? -1 : 1;
		}
		if(mDelta.getValue() != other.getDelta()) {
			return mDelta.getValue() < other.getDelta() ? 1 : -1;
		}
		
		if(!(other instanceof KeySignature)) {
			return 1;
		}
		
		KeySignature o = (KeySignature)other;
		if(mKey != o.mKey) {
			return mKey < o.mKey ? -1 : 1;
		}
		
		if(mScale != o.mScale) {
			return mKey < o.mScale ? -1 : 1;
		}
		
		return 0;
	}
}
